package com.fortune.cat.resolver;

import com.fortune.cat.bean.RequestRateLimiterConfig;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;
import java.util.Optional;

import static com.fortune.cat.filter.factory.DefaultRequestRateLimiterFilterFactory.EMPTY_KEY;

/**
 * @author zhaozeyang
 * @date 2019/4/26 10:32
 * @description
 */
public abstract class AbstractKeyResolver implements KeyResolver {

    protected RequestRateLimiterConfig requestRateLimiterConfig;

    public abstract Integer getType();

    public void setRequestRateLimiterConfig(RequestRateLimiterConfig requestRateLimiterConfig) {
        this.requestRateLimiterConfig = requestRateLimiterConfig;
    }

    @Override
    public Mono<String> resolve(ServerWebExchange exchange) {
        return Mono.just(Optional.ofNullable(doResolve(exchange)).map(p -> {
            if (Objects.nonNull(p)) {
                return p.concat("-").concat(((Route) exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR)).getId());
            } else {
                return null;
            }
        }).orElse(EMPTY_KEY));
    }

    /**
     * 获取key
     *
     * @param exchange
     * @return
     */
    abstract protected String doResolve(ServerWebExchange exchange);

}
